package net.sevear.chaos.recommend
{
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import mx.collections.ArrayCollection;
	
	public class ChaosActivateList extends ArrayCollection
	{
		public static const ALL_ITEMS_UPDATED:String = "All Items updated completed";
		public static const TIME_OUT:String = "Time out when update all items listen urls";
		public static const ITEM_UPDATED:String = "One Item updated";
		
		private var timer:Timer;
		private var iterator:int=1;
		private var origLen:int;
		private static const MAX_UPDATE_TIME:int = 6000;
		public function ChaosActivateList(source:Array=null)
		{
			super(source);
			origLen = this.length;
			timer = new Timer(1000);
			timer.addEventListener(TimerEvent.TIMER,onTimer);
			
		}
		
		public function startUpdate():void{
			if(this.length>0){
				iterator = 1;
				timer.start();
				processList();
			}
		}
		
		public function stopUpate():void{
			
		}
		
		private function processList():void{
//			var item:RecommendInfo = this.getItemAt(iterator-1) as RecommendInfo;
//			item.trackInfo.addEventListener(TrackInfo.UPDATE_DOUBAN_URL,onGetListenURL);
//			item.trackInfo.addEventListener(TrackInfo.FAILED_UPDATE_DOUBAN_URL,onFailedinGetListenURL);
//			item.trackInfo.getDBRadioURL();
		}
		
//		private function onGetListenURL(e:Event):void{
//			var track:TrackInfo = e.currentTarget as TrackInfo;
//			track.listenURL = track.downURLs[DBRadioKeeper.SOURCE_DB_RADIO] as String;
//			track.removeEventListener(TrackInfo.UPDATE_DOUBAN_URL,onGetListenURL);
//			track.removeEventListener(TrackInfo.FAILED_UPDATE_DOUBAN_URL,onFailedinGetListenURL);
//			iterator++;
//			if(iterator >= this.length+1){
//				timer.stop();
//				dispatchEvent(new Event(ALL_ITEMS_LISTEN_READY));
//			}
//		}
		
//		private function onFailedinGetListenURL(e:Event):void{
//			if(iterator >= this.length+1){
//				timer.stop();
//				dispatchEvent(new Event(ALL_ITEMS_LISTEN_READY));
//			}else{
//				processList();
//			}
//		}
		
		private function onTimer(e:TimerEvent):void{
			if(iterator >= this.length+1){
				timer.stop();
				dispatchEvent(new Event(ALL_ITEMS_UPDATED));
			}
			
			if(iterator<=this.length){
				processList();
			}
			
			if(timer.currentCount*1000>=MAX_UPDATE_TIME*this.origLen){
				timer.stop();
				dispatchEvent(new Event(TIME_OUT));
			}
		}
	}
}